// Copyright 2017 The Periph Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

// spi-io writes to an SPI port data from stdin and outputs to stdout or writes
// arguments and outputs hex encoded output.
//
// Usage:
//
//	echo -n -e '\x88\x00' | spi-io -b SPI0.0 | hexdump
//	spi-io -b SPI0.0 0x88 0
//
// For "read only" operation, writes zeros.
// For "write only" operation, ignore stdout.
package main

import (
	"log"
	"periph.io/x/conn/v3/physic"
	"periph.io/x/conn/v3/spi"
	"periph.io/x/conn/v3/spi/spireg"
	"periph.io/x/host/v3"
)

func main() {
	log.SetFlags(log.Lmicroseconds)

	if _, err := host.Init(); err != nil {
		log.Printf("leenux- host.Init: %v\n", err)
		return
	}
	s, err := spireg.Open("/dev/spidev3.0")
	if err != nil {
		log.Printf("leenux- open dev error:%v\n", err)
		return
	}
	defer s.Close()
	c, err := s.Connect(physic.MegaHertz, spi.Mode0, 16)
	if err != nil {
		log.Printf("leenux- connect dev error:%v\n", err)
		return
	}
	log.Printf("leenux- connect is %v\n", c)
	write := []byte("hello rk3566")
	read := make([]byte, len(write))
	if err = c.Tx(write, read); err != nil {
		log.Printf("leenux- write-read err %v\n", err)
		return
	}
	log.Printf("leenux- Get read %v\n", string(read))
}
